<?php

namespace App\Jobs;

use App\Goods;
use App\Order;
use App\OrderDetail;
use App\Sku;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class ReduceStock implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public $order_number;

    /**
     * Create a new job instance.
     *
     * @param $order_number
     */
    public function __construct($order_number)
    {
        $this->order_number=$order_number;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {

        $order=OrderDetail::where('order_id',$this->order_number)->get();
        Log::info("去除库存:".$this->order_number,[$order]);
        foreach ($order as $key=>$value){
            if ($value['sku_id']){
                $sku=Sku::find($value['sku_id']);
                if ($sku){
                    $sku->stock=$sku->stock-$value['number'];
                    $sku->save();
                }

            }else{
                $goods=Goods::find($value['goods_id']);
                $goods->stock=$goods->stock-$value['number'];
                $goods->save();
            }
        }

    }
}
